package com.util.utillib.extend

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast


fun Context.showMsg(msg: String?) {
    if (msg.isNullOrBlank()) return

    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}

fun Context.copyLabel(text: String?, resultMsg: String?) {
    if (text.isNullOrBlank()) return

    try {
        (getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).apply {
            setPrimaryClip(ClipData.newPlainText("Label", text))
        }
        showMsg(resultMsg)

    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
}

fun Context.appVersionCode(): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        packageManager.getPackageInfo(packageName, 0).longVersionCode.toInt()
    } else {
        packageManager.getPackageInfo(packageName, 0).versionCode
    }
}

@SuppressLint("QueryPermissionsNeeded")
fun Context.openSystemBrowser(url: String?) {
    if (url.isNullOrBlank()) return

    Intent(Intent.ACTION_VIEW).apply {
        data = Uri.parse(url)
        flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (resolveActivity(packageManager) != null) {
            startActivity(this)
        } else {
            startActivity(Intent.createChooser(this, ""))
        }
    }
}

@SuppressLint("QueryPermissionsNeeded")
fun Context.openDial(phone: String?, preCode: String? = null) {
    if (phone.isNullOrBlank()) return

    val uri = if (preCode.isNullOrBlank()) {
        "tel:0${Uri.encode(phone)}"
    } else {
        "tel:${Uri.encode("$preCode$phone")}"
    }

    Intent(Intent.ACTION_DIAL).apply {
        data = Uri.parse(uri)
        flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (resolveActivity(packageManager) != null) {
            startActivity(this)
        } else {
            startActivity(Intent.createChooser(this, ""))
        }
    }
}
